package cn.bocweb.spinning.view.forun;

import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.BindColor;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.DelForumBean;
import cn.bocweb.spinning.model.Bean.MyForumBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.common.BaseActivity;
import de.greenrobot.event.EventBus;

public class ForunMyTopicActivity extends BaseActivity {

    UserPresenter mPresenter;
    int page = 1;
    List<MyForumBean.DataBean> mDataBeanList;
    String userid;
    boolean isLastPage;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.forun_my_topic_list)
    RecyclerView forunMyTopicList;
    @Bind(R.id.forun_my_topic_refresh)
    SwipeRefreshLayout forunMyTopicRefresh;
    @BindColor(R.color.white)
    int white;

    ForunMyTopicAdapter forunMyTopicAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forun_my_topic);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);

        mDataBeanList = new ArrayList<>();
        mPresenter = new UserPresenterImp();
        forunMyTopicAdapter = new ForunMyTopicAdapter(mDataBeanList);

        initToolbar();
        initList();

        UserBean.DataEntity dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(this);
        userid = dataEntity.getUserid();
        mPresenter.getMyForum(page, userid);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public void onEventMainThread(MyForumBean bean) {
        if (forunMyTopicRefresh.isRefreshing()) {
            forunMyTopicRefresh.setRefreshing(false);
        }
        if (bean.getReturn_code() == 0) {
            if (bean.getData() != null) {
                mDataBeanList.addAll(bean.getData());
            }
            forunMyTopicAdapter.notifyDataSetChanged();
        } else if (bean.getReturn_code() == -202) {
            isLastPage = true;
            DeviceUtil.MyToast(this, "已经是最后一页");
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    public void onEventMainThread(DelForumBean bean) {
        if (bean.getReturn_code() == 0) {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    private void initList() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);

        forunMyTopicList.setLayoutManager(manager);
        forunMyTopicList.setAdapter(forunMyTopicAdapter);
        ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                mPresenter.delMyForum(userid, mDataBeanList.get(viewHolder.getAdapterPosition()).getId());
                mDataBeanList.remove(viewHolder.getAdapterPosition());
                forunMyTopicAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
            }

            @Override
            public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
                if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
                    //滑动时改变Item的透明度
                    final float alpha = 1 - Math.abs(dX) / (float) viewHolder.itemView.getWidth();
                    viewHolder.itemView.setAlpha(alpha);
                    viewHolder.itemView.setTranslationX(dX);
                }
            }
        });
        helper.attachToRecyclerView(forunMyTopicList);

        forunMyTopicRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                isLastPage = false;
                mDataBeanList.clear();
                forunMyTopicAdapter.notifyDataSetChanged();
                mPresenter.getMyForum(page, userid);
            }
        });

        forunMyTopicList.addOnScrollListener(new RecyclerView.OnScrollListener(){
            boolean isSlidingToLast = false;
            //用来标记是否正在向最后一个滑动，既是否向右滑动或向下滑动
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                LinearLayoutManager manager = (LinearLayoutManager)recyclerView.getLayoutManager();
                // 当不滚动时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //获取最后一个完全显示的ItemPosition
                    int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                    int totalItemCount = manager.getItemCount();

                    // 判断是否滚动到底部，并且是向右滚动
                    if (lastVisibleItem == (totalItemCount -1) && isSlidingToLast) {
                        //加载更多功能的代码
                        if (!isLastPage) {
                            page++;
                            mPresenter.getMyForum(page, userid);

                        } else {
//                            DeviceUtil.MyToast(ForunMyTopicActivity.this, "已经是最后一页");
                        }
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //dx用来判断横向滑动方向，dy用来判断纵向滑动方向
                if(dy > 0){
                    //大于0表示，正在向右滚动
                    isSlidingToLast = true;
                }else{
                    //小于等于0 表示停止或向左滚动
                    isSlidingToLast = false;
                }

            }
        });


        forunMyTopicAdapter.setOnItemClickListener(new ForunMyTopicAdapter.OnItemClickListener() {
            @Override
            public void onClick(String id) {
                Intent intent = new Intent(ForunMyTopicActivity.this, ForunDetailActivity.class);
                intent.putExtra(Constant.TO_FORUM_DETAIL, id);
                startActivity(intent);
            }
        });
    }

    private void initToolbar() {
        toolbar.setTitle("我的话题");
        toolbar.setTitleTextColor(white);
        toolbar.setNavigationIcon(R.mipmap.btn_exit);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}
